// src/pages/Home/DataAnalysis/Dashboard/index.js
import React, { useState } from 'react';
import {
  Row, Col, Card, Button, Select, Empty,
  Space, Divider, Form, Input, Alert, Modal,
  Checkbox, Collapse, Tag, Switch, Slider
} from 'antd';
import {
  PlusOutlined,
  SaveOutlined,
  BarChartOutlined,
  PieChartOutlined,
  LineChartOutlined,
  AreaChartOutlined,
  DatabaseOutlined,
  EditOutlined,
  DeleteOutlined,
  RadarChartOutlined,
  DotChartOutlined,
  HeatMapOutlined,
  FundOutlined,
  SettingOutlined
} from '@ant-design/icons';
import ReactECharts from 'echarts-for-react';

const { Option } = Select;
const { Panel } = Collapse;
const { TextArea } = Input;

const Dashboard = () => {
  const [dashboards, setDashboards] = useState([
    {
      id: 1,
      name: '销售数据分析',
      createdAt: '2023-11-15',
      charts: [
        {
          id: 1,
          title: '月度销售趋势',
          type: 'line',
          dataSource: 'sales_data',
          xAxis: 'month',
          yAxis: 'revenue',
          smooth: true,
          areaStyle: false,
          markPoint: {
            showMax: true,
            showMin: true
          },
          data: [
            { month: '1月', revenue: 820 },
            { month: '2月', revenue: 932 },
            { month: '3月', revenue: 901 },
            { month: '4月', revenue: 934 },
            { month: '5月', revenue: 1290 },
            { month: '6月', revenue: 1330 }
          ]
        },
        {
          id: 2,
          title: '产品类别分布',
          type: 'pie',
          dataSource: 'product_data',
          nameField: 'category',
          valueField: 'count',
          roseType: false,
          labelShow: true,
          data: [
            { category: '电子产品', count: 45 },
            { category: '服装', count: 25 },
            { category: '食品', count: 20 },
            { category: '其他', count: 10 }
          ]
        }
      ]
    }
  ]);

  const [dataSources] = useState([
    { id: 'sales_data', name: '销售数据表' },
    { id: 'product_data', name: '产品数据表' },
    { id: 'customer_data', name: '客户数据表' },
    { id: 'finance_data', name: '财务数据表' },
    { id: 'hr_data', name: '人力资源数据表' }
  ]);

  const [selectedDashboard, setSelectedDashboard] = useState(dashboards[0]);
  const [isChartModalVisible, setIsChartModalVisible] = useState(false);
  const [editingChart, setEditingChart] = useState(null);
  const [chartForm] = Form.useForm();

  const chartTypes = [
    { value: 'line', label: '折线图', icon: <LineChartOutlined /> },
    { value: 'bar', label: '柱状图', icon: <BarChartOutlined /> },
    { value: 'pie', label: '饼图', icon: <PieChartOutlined /> },
    { value: 'area', label: '面积图', icon: <AreaChartOutlined /> },
    { value: 'radar', label: '雷达图', icon: <RadarChartOutlined /> },
    { value: 'scatter', label: '散点图', icon: <DotChartOutlined /> },
    { value: 'heatmap', label: '热力图', icon: <HeatMapOutlined /> },
    { value: 'funnel', label: '漏斗图', icon: <FundOutlined /> }
  ];

  const createNewDashboard = () => {
    const newDashboard = {
      id: Date.now(),
      name: `仪表板 ${dashboards.length + 1}`,
      createdAt: new Date().toISOString().split('T')[0],
      charts: []
    };
    setDashboards([...dashboards, newDashboard]);
    setSelectedDashboard(newDashboard);
  };

  const addNewChart = () => {
    setEditingChart(null);
    chartForm.resetFields();
    setIsChartModalVisible(true);
  };

  const editChart = (chart) => {
    setEditingChart(chart);
    chartForm.setFieldsValue({
      ...chart,
      smooth: chart.smooth || false,
      areaStyle: chart.areaStyle || false,
      roseType: chart.roseType || false,
      labelShow: chart.labelShow !== undefined ? chart.labelShow : true,
      stack: chart.stack || false,
      horizontal: chart.horizontal || false
    });
    setIsChartModalVisible(true);
  };

  const deleteChart = (chartId) => {
    const updatedDashboards = dashboards.map(dashboard =>
      dashboard.id === selectedDashboard.id
        ? {
            ...dashboard,
            charts: dashboard.charts.filter(chart => chart.id !== chartId)
          }
        : dashboard
    );

    setDashboards(updatedDashboards);
    setSelectedDashboard(updatedDashboards.find(d => d.id === selectedDashboard.id));
  };

  const handleChartConfigFinish = (values) => {
    const chartData = generateSampleData(values);

    if (editingChart) {
      // 更新图表
      const updatedDashboards = dashboards.map(dashboard =>
        dashboard.id === selectedDashboard.id
          ? {
              ...dashboard,
              charts: dashboard.charts.map(chart =>
                chart.id === editingChart.id
                  ? { ...values, id: editingChart.id, data: chartData }
                  : chart
              )
            }
          : dashboard
      );

      setDashboards(updatedDashboards);
      setSelectedDashboard(updatedDashboards.find(d => d.id === selectedDashboard.id));
    } else {
      // 添加新图表
      const newChart = {
        id: Date.now(),
        ...values,
        data: chartData
      };

      const updatedDashboards = dashboards.map(dashboard =>
        dashboard.id === selectedDashboard.id
          ? { ...dashboard, charts: [...dashboard.charts, newChart] }
          : dashboard
      );

      setDashboards(updatedDashboards);
      setSelectedDashboard(updatedDashboards.find(d => d.id === selectedDashboard.id));
    }

    setIsChartModalVisible(false);
  };

  const generateSampleData = (config) => {
    // 根据图表类型和数据源生成示例数据
    switch (config.type) {
      case 'line':
      case 'bar':
      case 'area':
        return [
          { [config.xAxis]: '一月', [config.yAxis]: Math.floor(Math.random() * 1000) },
          { [config.xAxis]: '二月', [config.yAxis]: Math.floor(Math.random() * 1000) },
          { [config.xAxis]: '三月', [config.yAxis]: Math.floor(Math.random() * 1000) },
          { [config.xAxis]: '四月', [config.yAxis]: Math.floor(Math.random() * 1000) },
          { [config.xAxis]: '五月', [config.yAxis]: Math.floor(Math.random() * 1000) },
          { [config.xAxis]: '六月', [config.yAxis]: Math.floor(Math.random() * 1000) }
        ];
      case 'pie':
        return [
          { [config.nameField]: '类别A', [config.valueField]: Math.floor(Math.random() * 100) },
          { [config.nameField]: '类别B', [config.valueField]: Math.floor(Math.random() * 100) },
          { [config.nameField]: '类别C', [config.valueField]: Math.floor(Math.random() * 100) },
          { [config.nameField]: '类别D', [config.valueField]: Math.floor(Math.random() * 100) }
        ];
      case 'radar':
        return [
          { dimension: '销售', value: Math.floor(Math.random() * 100) },
          { dimension: '市场', value: Math.floor(Math.random() * 100) },
          { dimension: '研发', value: Math.floor(Math.random() * 100) },
          { dimension: '客服', value: Math.floor(Math.random() * 100) },
          { dimension: '财务', value: Math.floor(Math.random() * 100) }
        ];
      case 'scatter':
        const scatterData = [];
        for (let i = 0; i < 20; i++) {
          scatterData.push([
            Math.floor(Math.random() * 100),
            Math.floor(Math.random() * 100),
            Math.floor(Math.random() * 100)
          ]);
        }
        return scatterData;
      case 'heatmap':
        const heatmapData = [];
        const days = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
        const hours = ['0点', '2点', '4点', '6点', '8点', '10点', '12点', '14点', '16点', '18点', '20点', '22点'];
        days.forEach((day, i) => {
          hours.forEach((hour, j) => {
            heatmapData.push([i, j, Math.floor(Math.random() * 100)]);
          });
        });
        return {
          xAxis: hours,
          yAxis: days,
          data: heatmapData
        };
      case 'funnel':
        return [
          { value: 60, name: '访问' },
          { value: 40, name: '咨询' },
          { value: 20, name: '订单' },
          { value: 80, name: '点击' },
          { value: 100, name: '展现' }
        ];
      default:
        return [];
    }
  };

  const getChartOption = (chart) => {
    switch (chart.type) {
      case 'line':
        return {
          title: { text: chart.title, left: 'center' },
          tooltip: { trigger: 'axis' },
          xAxis: {
            type: 'category',
            data: chart.data.map(item => item[chart.xAxis])
          },
          yAxis: { type: 'value' },
          series: [{
            data: chart.data.map(item => item[chart.yAxis]),
            type: 'line',
            smooth: chart.smooth,
            areaStyle: chart.areaStyle ? {} : undefined,
            markPoint: chart.markPoint?.showMax || chart.markPoint?.showMin ? {
              data: [
                chart.markPoint.showMax ? { type: 'max', name: '最大值' } : null,
                chart.markPoint.showMin ? { type: 'min', name: '最小值' } : null
              ].filter(Boolean)
            } : undefined
          }]
        };
      case 'bar':
        return {
          title: { text: chart.title, left: 'center' },
          tooltip: { trigger: 'axis' },
          xAxis: {
            type: chart.horizontal ? 'value' : 'category',
            data: chart.horizontal ? undefined : chart.data.map(item => item[chart.xAxis])
          },
          yAxis: {
            type: chart.horizontal ? 'category' : 'value',
            data: chart.horizontal ? chart.data.map(item => item[chart.xAxis]) : undefined
          },
          series: [{
            data: chart.data.map(item => item[chart.yAxis]),
            type: 'bar',
            stack: chart.stack ? 'total' : undefined,
            label: {
              show: true,
              position: chart.horizontal ? 'right' : 'inside'
            }
          }]
        };
      case 'pie':
        return {
          title: { text: chart.title, left: 'center' },
          tooltip: { trigger: 'item' },
          series: [{
            data: chart.data.map(item => ({
              name: item[chart.nameField],
              value: item[chart.valueField]
            })),
            type: 'pie',
            roseType: chart.roseType ? 'radius' : undefined,
            label: {
              show: chart.labelShow
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }]
        };
      case 'area':
        return {
          title: { text: chart.title, left: 'center' },
          tooltip: { trigger: 'axis' },
          xAxis: {
            type: 'category',
            data: chart.data.map(item => item[chart.xAxis])
          },
          yAxis: { type: 'value' },
          series: [{
            data: chart.data.map(item => item[chart.yAxis]),
            type: 'line',
            areaStyle: {},
            smooth: chart.smooth
          }]
        };
      case 'radar':
        return {
          title: { text: chart.title, left: 'center' },
          tooltip: {},
          radar: {
            indicator: chart.data.map(item => ({
              name: item.dimension,
              max: 100
            }))
          },
          series: [{
            type: 'radar',
            data: [{
              value: chart.data.map(item => item.value),
              name: '指标'
            }]
          }]
        };
      case 'scatter':
        return {
          title: { text: chart.title, left: 'center' },
          tooltip: { trigger: 'item' },
          xAxis: {},
          yAxis: {},
          series: [{
            type: 'scatter',
            data: chart.data,
            symbolSize: function (data) {
              return Math.sqrt(data[2]) / 2;
            }
          }]
        };
      case 'heatmap':
        return {
          title: { text: chart.title, left: 'center' },
          tooltip: {
            position: 'top'
          },
          xAxis: {
            type: 'category',
            data: chart.data.xAxis
          },
          yAxis: {
            type: 'category',
            data: chart.data.yAxis
          },
          visualMap: {
            min: 0,
            max: 100,
            calculable: true,
            orient: 'horizontal',
            left: 'center'
          },
          series: [{
            name: 'heatmap',
            type: 'heatmap',
            data: chart.data.data,
            label: {
              show: true
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }]
        };
      case 'funnel':
        return {
          title: { text: chart.title, left: 'center' },
          tooltip: {
            trigger: 'item',
            formatter: "{a} <br/>{b} : {c}%"
          },
          series: [{
            name: '漏斗图',
            type: 'funnel',
            left: '10%',
            top: 60,
            bottom: 60,
            width: '80%',
            min: 0,
            max: 100,
            minSize: '0%',
            maxSize: '100%',
            sort: 'descending',
            gap: 2,
            label: {
              show: true,
              position: 'inside'
            },
            labelLine: {
              length: 10,
              lineStyle: {
                width: 1,
                type: 'solid'
              }
            },
            itemStyle: {
              borderColor: '#fff',
              borderWidth: 1
            },
            emphasis: {
              label: {
                fontSize: 20
              }
            },
            data: chart.data
          }]
        };
      default:
        return {};
    }
  };

  return (
    <div className="data-analysis-dashboard">
      <div style={{ marginBottom: 24 }}>
        <Space size="large">
          <Select
            style={{ width: 200 }}
            placeholder="选择仪表板"
            value={selectedDashboard?.id}
            onChange={(value) => setSelectedDashboard(dashboards.find(d => d.id === value))}
          >
            {dashboards.map(dashboard => (
              <Option key={dashboard.id} value={dashboard.id}>
                {dashboard.name}
              </Option>
            ))}
          </Select>

          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={createNewDashboard}
          >
            新建仪表板
          </Button>

          <Button
            icon={<PlusOutlined />}
            onClick={addNewChart}
          >
            添加图表
          </Button>

          <Button
            type="primary"
            icon={<SaveOutlined />}
          >
            保存仪表板
          </Button>
        </Space>
      </div>

      <Divider />

      {selectedDashboard ? (
        <div>
          {selectedDashboard.charts.length > 0 ? (
            <Row gutter={[16, 16]}>
              {selectedDashboard.charts.map(chart => (
                <Col span={12} key={chart.id}>
                  <Card
                    title={chart.title}
                    size="small"
                    extra={
                      <Space>
                        <Button
                          type="link"
                          icon={<EditOutlined />}
                          onClick={() => editChart(chart)}
                        />
                        <Button
                          type="link"
                          icon={<DeleteOutlined />}
                          onClick={() => deleteChart(chart.id)}
                          danger
                        />
                      </Space>
                    }
                  >
                    <ReactECharts
                      option={getChartOption(chart)}
                      style={{ height: 300 }}
                    />
                  </Card>
                </Col>
              ))}
            </Row>
          ) : (
            <div style={{ textAlign: 'center', padding: '48px 0' }}>
              <Empty
                description={
                  <span>
                    当前仪表板没有图表，请点击"添加图表"创建第一个图表
                  </span>
                }
              >
                <Button type="primary" onClick={addNewChart} icon={<PlusOutlined />}>
                  添加图表
                </Button>
              </Empty>
            </div>
          )}
        </div>
      ) : (
        <div style={{ textAlign: 'center', padding: '48px 0' }}>
          <Empty description="请选择或创建一个仪表板" />
        </div>
      )}

      {/* 图表配置模态框 */}
      <Modal
        title={editingChart ? "编辑图表" : "添加图表"}
        open={isChartModalVisible}
        onCancel={() => setIsChartModalVisible(false)}
        footer={null}
        width={800}
      >
        <Form
          form={chartForm}
          layout="vertical"
          onFinish={handleChartConfigFinish}
          initialValues={editingChart || {}}
        >
          <Form.Item
            name="title"
            label="图表标题"
            rules={[{ required: true, message: '请输入图表标题' }]}
          >
            <Input placeholder="例如：月度销售趋势" />
          </Form.Item>

          <Form.Item
            name="type"
            label="图表类型"
            rules={[{ required: true, message: '请选择图表类型' }]}
          >
            <Select placeholder="请选择图表类型">
              {chartTypes.map(chartType => (
                <Option key={chartType.value} value={chartType.value}>
                  <Space>
                    {chartType.icon}
                    {chartType.label}
                  </Space>
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="dataSource"
            label="数据源"
            rules={[{ required: true, message: '请选择数据源' }]}
          >
            <Select placeholder="请选择数据源">
              {dataSources.map(source => (
                <Option key={source.id} value={source.id}>
                  <Space>
                    <DatabaseOutlined />
                    {source.name}
                  </Space>
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item noStyle shouldUpdate>
            {({ getFieldValue }) => {
              const chartType = getFieldValue('type');
              const dataSource = getFieldValue('dataSource');

              if (!chartType || !dataSource) return null;

              switch (chartType) {
                case 'line':
                case 'area':
                  return (
                    <>
                      <Space>
                        <Form.Item
                          name="xAxis"
                          label="X轴字段"
                          rules={[{ required: true, message: '请选择X轴字段' }]}
                        >
                          <Input placeholder="例如：month" />
                        </Form.Item>

                        <Form.Item
                          name="yAxis"
                          label="Y轴字段"
                          rules={[{ required: true, message: '请选择Y轴字段' }]}
                        >
                          <Input placeholder="例如：revenue" />
                        </Form.Item>
                      </Space>

                      <Collapse bordered={false} size="small">
                        <Panel header={<Space><SettingOutlined /><span>高级配置</span></Space>} key="1">
                          <Space wrap>
                            <Form.Item name="smooth" valuePropName="checked">
                              <Checkbox>平滑曲线</Checkbox>
                            </Form.Item>

                            {chartType === 'line' && (
                              <Form.Item name="areaStyle" valuePropName="checked">
                                <Checkbox>面积图</Checkbox>
                              </Form.Item>
                            )}

                            <Form.Item name="stack" valuePropName="checked">
                              <Checkbox>堆叠显示</Checkbox>
                            </Form.Item>
                          </Space>

                          <div style={{ marginTop: 12 }}>标记点：</div>
                          <Space>
                            <Form.Item name={['markPoint', 'showMax']} valuePropName="checked">
                              <Checkbox>最大值</Checkbox>
                            </Form.Item>
                            <Form.Item name={['markPoint', 'showMin']} valuePropName="checked">
                              <Checkbox>最小值</Checkbox>
                            </Form.Item>
                          </Space>
                        </Panel>
                      </Collapse>
                    </>
                  );
                case 'bar':
                  return (
                    <>
                      <Space>
                        <Form.Item
                          name="xAxis"
                          label="X轴字段"
                          rules={[{ required: true, message: '请选择X轴字段' }]}
                        >
                          <Input placeholder="例如：month" />
                        </Form.Item>

                        <Form.Item
                          name="yAxis"
                          label="Y轴字段"
                          rules={[{ required: true, message: '请选择Y轴字段' }]}
                        >
                          <Input placeholder="例如：revenue" />
                        </Form.Item>
                      </Space>

                      <Collapse bordered={false} size="small">
                        <Panel header={<Space><SettingOutlined /><span>高级配置</span></Space>} key="1">
                          <Space wrap>
                            <Form.Item name="horizontal" valuePropName="checked">
                              <Checkbox>横向柱状图</Checkbox>
                            </Form.Item>

                            <Form.Item name="stack" valuePropName="checked">
                              <Checkbox>堆叠显示</Checkbox>
                            </Form.Item>
                          </Space>
                        </Panel>
                      </Collapse>
                    </>
                  );
                case 'pie':
                  return (
                    <>
                      <Space>
                        <Form.Item
                          name="nameField"
                          label="名称字段"
                          rules={[{ required: true, message: '请选择名称字段' }]}
                        >
                          <Input placeholder="例如：category" />
                        </Form.Item>

                        <Form.Item
                          name="valueField"
                          label="值字段"
                          rules={[{ required: true, message: '请选择值字段' }]}
                        >
                          <Input placeholder="例如：count" />
                        </Form.Item>
                      </Space>

                      <Collapse bordered={false} size="small">
                        <Panel header={<Space><SettingOutlined /><span>高级配置</span></Space>} key="1">
                          <Space wrap>
                            <Form.Item name="roseType" valuePropName="checked">
                              <Checkbox>南丁格尔玫瑰图</Checkbox>
                            </Form.Item>
                            <Form.Item name="labelShow" valuePropName="checked">
                              <Checkbox>显示标签</Checkbox>
                            </Form.Item>
                          </Space>
                        </Panel>
                      </Collapse>
                    </>
                  );
                case 'radar':
                  return (
                    <Space>
                      <Form.Item
                        name="dimension"
                        label="维度字段"
                        rules={[{ required: true, message: '请输入维度字段' }]}
                      >
                        <Input placeholder="例如：dimension" />
                      </Form.Item>

                      <Form.Item
                        name="value"
                        label="值字段"
                        rules={[{ required: true, message: '请输入值字段' }]}
                      >
                        <Input placeholder="例如：value" />
                      </Form.Item>
                    </Space>
                  );
                case 'scatter':
                  return (
                    <Space>
                      <Form.Item
                        name="xField"
                        label="X轴字段"
                        rules={[{ required: true, message: '请输入X轴字段' }]}
                      >
                        <Input placeholder="例如：x" />
                      </Form.Item>

                      <Form.Item
                        name="yField"
                        label="Y轴字段"
                        rules={[{ required: true, message: '请输入Y轴字段' }]}
                      >
                        <Input placeholder="例如：y" />
                      </Form.Item>

                      <Form.Item
                        name="sizeField"
                        label="大小字段"
                        rules={[{ required: true, message: '请输入大小字段' }]}
                      >
                        <Input placeholder="例如：size" />
                      </Form.Item>
                    </Space>
                  );
                case 'heatmap':
                  return (
                    <Space>
                      <Form.Item
                        name="xField"
                        label="X轴字段"
                        rules={[{ required: true, message: '请输入X轴字段' }]}
                      >
                        <Input placeholder="例如：hour" />
                      </Form.Item>

                      <Form.Item
                        name="yField"
                        label="Y轴字段"
                        rules={[{ required: true, message: '请输入Y轴字段' }]}
                      >
                        <Input placeholder="例如：day" />
                      </Form.Item>

                      <Form.Item
                        name="valueField"
                        label="值字段"
                        rules={[{ required: true, message: '请输入值字段' }]}
                      >
                        <Input placeholder="例如：value" />
                      </Form.Item>
                    </Space>
                  );
                case 'funnel':
                  return (
                    <Space>
                      <Form.Item
                        name="nameField"
                        label="名称字段"
                        rules={[{ required: true, message: '请输入名称字段' }]}
                      >
                        <Input placeholder="例如：stage" />
                      </Form.Item>

                      <Form.Item
                        name="valueField"
                        label="值字段"
                        rules={[{ required: true, message: '请输入值字段' }]}
                      >
                        <Input placeholder="例如：value" />
                      </Form.Item>
                    </Space>
                  );
                default:
                  return null;
              }
            }}
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                {editingChart ? "更新图表" : "添加图表"}
              </Button>
              <Button onClick={() => setIsChartModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Dashboard;
